import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
// import { routerRedux, Route, Switch } from 'dva/router';
import { Form, Input, Select, Button, Badge } from 'antd';
import StandardTable from '@/components/StandardTable';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import AdSelect from '@/components/AdSelect';
import { codes, STATUS, EventType, NoticeMode, statusMap } from './utils';
import { formateDateToMin } from '@/utils/common';
import RightDraw from '@/components/RightDraw';
import ContentDetails from './ContentDetails';


const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

@ManageList
@connect(({ interfaceContent, common, loading }) => ({
    interfaceContent,
    loading: loading.effects['interfaceContent/interfaceContentList'],
    dictObject: common.dictObject,
}))
@Form.create()
export default class InterfaceContentList extends Component {
    state = {
        expandForm: false,
        selectedRows: [],
        visible: false,
        checkIds: [],
        isAbled: true,
        formValues: {},
    };
    className = 'interfaceContent';

    columns = [
        {
            title: '业务单号',
            dataIndex: 'businessCode',
            render: (text, record) => <a onClick={e => this.showDetail(e, record)} title={text}>
                {text}
            </a>,
            width: 200,
        },
        {
            title: '业务单ID',
            dataIndex: 'businessId',
            render: text => <span title={text}>{text}</span>,
            width: 250,
        },
        {
            title: '业务类型编码',
            dataIndex: 'businessTypeCode',
            render: text => <span title={text}>{text}</span>,
            width: 200,
        },
        {
            title: '业务类型名称',
            dataIndex: 'businessType',
            render: text => <span title={text}>{text}</span>,
            width: 200,
        },
        {
            title: '发送方',
            dataIndex: 'senderSys',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '接收方',
            dataIndex: 'receiverSys',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '状态',
            dataIndex: 'dealStatus',
            render: (text) => {
                const val = <AdSelect data={STATUS} value={text} onlyRead={true} />;
                return <Badge status={statusMap[text]} text={val} />
            },
            width: 100,
        },
        {
            title: '请求报文',
            dataIndex: 'requestData',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '响应报文',
            dataIndex: 'responseData',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '重试次数',
            dataIndex: 'retryCount',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '最新执行时间',
            dataIndex: 'execTime',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '创建人账号',
            dataIndex: 'createBy',
            render: text => <AdSelect data={NoticeMode} value={text} onlyRead={true} />,
        },
        {
            title: '创建人时间',
            dataIndex: 'createTime',
            render: text => <span title={text}>{text}</span>,
        },

        {
            title: '修改人账号',
            dataIndex: 'updateBy',
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
    ];
    componentDidMount() {
        this.getContentList();
    }

    //详情：
    showDetail = (e, record) => {
        e.stopPropagation();
        const { dispatch } = this.props;
        const { id } = record;
        // console.log('senderId', record.senderId);
        dispatch({
            type: 'interfaceContent/interfaceContentDetails',
            payload: { id },
            callback: res => {
                this.setState({
                    isAbled: ['fail', 'FAIL', 'NOTlOAD', 'LOADFAIL'].indexOf(record.dealStatus) === -1 ? true : false,
                });
            },
        });
        this.setState(
            {
                checkId: id,
                rowDetails: record,
            },
            () => {
                this.setState({
                    visible: true,
                });
            }
        );
    };

    getContentList = (params = {}) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'interfaceContent/interfaceContentList',
            payload: params,
        });
    };

    handleEdit = () => {
        router.push(`/interface/interfaeContent/ContentEdit/${this.state.checkId}`);
        this.closeDetail();
    };
    //重置
    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
        });
        this.getContentList();
    };

    toggleForm = () => {
        const { expandForm } = this.state;
        this.setState({
            expandForm: !expandForm,
        });
    };

    handleSelectRows = rows => {
        console.log('选择', rows);
        let ids = [];
        if (Array.isArray(rows) && rows.length > 0) {
            rows.map((item, i) => {
                ids.push(item.id);
            });
        }
        this.setState({
            selectedRows: rows,
            checkIds: ids,
        });
    };

    //查询
    handleSearch = values => {
        // if (!values) {
        //   return;
        // }
        const { ...value } = values;
        this.setState({
            formValues: value,
        });
        this.getContentList(value);
    };
    // 分页操作：改参数
    handleStandardTableChange = param => {
        const { formValues } = this.state;
        const params = {
            ...formValues,
            ...param,
        };
        this.getContentList(params);
    };

    //立即执行：
    retry = (single) => {
        const { dispatch } = this.props;
        const { checkIds, formValues, checkId } = this.state;
        let params = {};
        if (single === 1) {
            params.ids = [checkId]
        } else {
            params.ids = checkIds;
        }
        console.log('params', params)
        dispatch({
            type: 'interfaceContent/retryInterfaceContent',
            payload: params,
            callback: res => {
                console.log('res', res);
                this.getContentList(formValues);
                if (single) {
                    dispatch({
                        type: 'interfaceType/interfaceContentDetails',
                        payload: { id: checkId },
                    });
                }
            },
        });
    };

    closeDetail = () => {
        this.setState({
            visible: false
        })
    }
    render() {
        const {
            loading,
            interfaceContent: { interfaceContentList },
            form,
            isMobile,
            dictObject,
        } = this.props;
        const { getFieldDecorator } = form;
        const { selectedRows, expandForm, visible, isAbled, checkId } = this.state;
        const firstFormItem = (
            <FormItem label="业务类型编码">
                {getFieldDecorator('businessTypeCode')(<Input placeholder="请输入" />)}
            </FormItem>
        );
        const secondFormItem = (
            <FormItem label="业务单号">
                {getFieldDecorator('businessCode')(<Input placeholder="请输入" />)}
            </FormItem>
        );

        // secondForm 参数
        const otherFormItem = [
            [
                <FormItem label="接收方">
                    {getFieldDecorator('receiverSys')(<Input placeholder="请输入" />)}
                </FormItem>,
            ],
            [<FormItem label="发送方">
                {getFieldDecorator('senderSys')(<Input placeholder="请输入" />)}
            </FormItem>,
            <FormItem label="处理状态">
                {getFieldDecorator('dealStatus')(
                    <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
                        <Option value="">请选择</Option>
                        {STATUS.map(v => {
                            return <Option value={v.code}>{v.value}</Option>;
                        })}
                    </Select>
                )}
            </FormItem>,
            <FormItem label="业务类型">
                {getFieldDecorator('businessType')(<Input placeholder="请输入" />)}
            </FormItem>,

            ],
            ['operatorButtons']
        ];

        const rightDrawParams = {
            isMobile,
            visible,
            title: '接口内容详情',
            closeDetail: this.closeDetail,
            buttons: (
                <span>
                    {!isAbled &&
                        <Button.Group>
                            <Button onClick={() => this.retry(1)}>立即执行</Button>
                            <Button type="primary" onClick={this.handleEdit}>编辑</Button>
                        </Button.Group>}
                </span >
            ),
        };

        const selectFormParams = {
            firstFormItem,
            secondFormItem,
            otherFormItem,
            form,
            className: this.className,
            handleFormReset: this.handleFormReset,
            handleSearch: this.handleSearch,
            toggleForm: this.toggleForm,
        };
        const tableButtonsParams = {
            show: true,
            // handleAdd: this.handleAdd,
            buttons: (
                <Button onClick={this.retry} disabled={selectedRows.length > 0 ? false : true}>
                    立即执行
                </Button>
            ),
            selectedRows: selectedRows,
        };
        console.log('interfaceContentList', interfaceContentList)
        return (
            <Fragment>
                <SelectForm {...selectFormParams} />
                <TableButtons {...tableButtonsParams} />
                <StandardTable
                    selectedRows={selectedRows}
                    loading={loading}
                    data={interfaceContentList}
                    columns={this.columns}
                    onSelectRow={this.handleSelectRows}
                    onPaginationChange={this.handleStandardTableChange}
                    expandForm={expandForm}
                    className={this.className}
                    code={codes.page}
                    getCheckboxProps={record => {
                        return ['fail', 'FAIL', 'NOTlOAD', 'LOADFAIL'].indexOf(record.dealStatus) === -1;
                    }}
                />
                <RightDraw {...rightDrawParams}>
                    <ContentDetails checkId={checkId} isMobile={isMobile} />
                </RightDraw>
            </Fragment >
        );
    }
}
